package com.ysm.smfu.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.activity.AboutActivity;
import com.ysm.smfu.activity.AccountDetailActivity;
import com.ysm.smfu.activity.BonusDetailActivity;
import com.ysm.smfu.activity.FoundActivity;
import com.ysm.smfu.activity.MySettingActivity;
import com.ysm.smfu.activity.My_XiuGai_Activity;
import com.ysm.smfu.area.Area;
import com.ysm.smfu.area.CityUtil2;
import com.ysm.smfu.area.FileUtil;
import com.ysm.smfu.bean.Account;
import com.ysm.smfu.bean.Friend;
import com.ysm.smfu.bean.StateCount;
import com.ysm.smfu.bean.User;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.manager.GlideCircleTransform;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.CircleUtil;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.BounceScrollView;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.db.DBManager;

public class MyFragment extends MyBaseFragment {

    private static final int REQUEST_CODE_ASK_CALL_PHONE = 100;
    @BindView(R.id.activity_main_top_bar)
    AutoRelativeLayout activity_main_top_bar;

    @BindView(R.id.scroll_view)
    BounceScrollView scrollView;

    //    头像
    @BindView(R.id.iv_fragment_me_headimg)
    ImageView ivFragmentMeHeadimg;
    //    昵称
    @BindView(R.id.tv_fragment_me_nickname)
    TextView tvFragmentMeNickname;

    @BindView(R.id.img_level)
    ImageView img_level;
    @BindView(R.id.proxyImg)
    ImageView proxyImg;

    @BindView(R.id.phone)
    TextView phoneT;
    @BindView(R.id.yuEr)
    TextView yuEr;
    @BindView(R.id.yongJin)
    TextView yongJin;
    @BindView(R.id.duiHuanQuan)
    TextView duiHuanQuan;
    @BindView(R.id.unFuKuan)
    TextView unFuKuan;
    @BindView(R.id.unShouHuo)
    TextView unShouHuo;
    @BindView(R.id.unFaHuo)
    TextView unFaHuo;
    private SharedPreferences currShared;
    //    客服电话
    private final String phoneN = SpKey.SEAVERNUMBER;
    private String codePre;
    private String codeSuf;
    private Account account;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bitmap bitmap = intent.getParcelableExtra("image");
            String nc = intent.getStringExtra("nc");
            String sex = intent.getStringExtra("sex");
            String sr = intent.getStringExtra("sr");
            String dq = intent.getStringExtra("dq");
            String is_business = intent.getStringExtra("is_business");

            // 保存到本地
            currShared.edit().putString(SpKey.NC, nc).apply();
            currShared.edit().putString(SpKey.SEX, sex).apply();
            currShared.edit().putString(SpKey.SR, sr).apply();
            currShared.edit().putString(SpKey.DQ, dq).apply();
            currShared.edit().putString(SpKey.IS_BUSINESS, is_business).apply();
//          是否只更新了头像
            boolean isInfo = intent.getBooleanExtra("isInfo", false);
            Bitmap circleBitmap = CircleUtil.toRoundBitmap(UIUtils.getContext(), bitmap);
            if (circleBitmap != null)
                ivFragmentMeHeadimg.setImageBitmap(circleBitmap);
            tvFragmentMeNickname.setText(nc);
//                因为接口变动和二维码不添加logo原因，不再需要保持头像到本地
//                MyImageBitmapUtil.saveBitmapLoc(circleBitmap, name);
            isUpdateImg = true;
//                用户修改了个人信息包含头像，需要保持到数据库
            if (!isInfo)
                getUserInfo();
        }
    };
    private SharedPreferences sp;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
//                初始化城市数据
                String area_str;
                if (sp == null)
                    sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
                String str = sp.getString(SpKey.AAASSEST2, "");
                if (!TextUtils.isEmpty(str))
                    area_str = str;
                else {
                    area_str = FileUtil.readAssets(UIUtils.getContext(), "a2.json");
                    sp.edit().putString(SpKey.AAASSEST2, area_str).apply();
                }
                Gson gson = new Gson();
                Area area = gson.fromJson(area_str, Area.class);
                CityUtil2 cityUtil2 = new CityUtil2(area);
                cityUtil2.initProvince();
                cityUtil2.initCity();
                cityUtil2.initCountry();
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(UIUtils.getContext(), R.layout.fragment_my, null);
        ButterKnife.bind(this, view);
        getConfigAndSet();
        phoneT.setText(String.valueOf(phoneN));
//        注册广播接收头像变化
        registerImageBroadCase();
        initTopBar();
        return view;
    }

    /**
     * 沉浸式状态栏实现
     */
    private void initTopBar() {
        StatusBarCompat.compat(getActivity(), getResources().getColor(R.color.translate));
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        AutoLinearLayout.LayoutParams layoutParams = (AutoLinearLayout.LayoutParams) activity_main_top_bar.getLayoutParams();
        layoutParams.topMargin = StatusBarCompat.getStatusBarHeight(getContext());
        activity_main_top_bar.setLayoutParams(layoutParams);
        activity_main_top_bar.setBackgroundResource(R.color.translate);
//        }
    }

    @Override
    public void afterOnResume() {
        super.afterOnResume();

        if (BaseProtocal.isGoLogin(true)) {
            resetAllData();
            return;
        }
//        如果用户从商城更新用户信息，需要通过onResume方法更新，会调用多次，不能做太多操作
//        registerForUserInfo_onLine();
//        从商城返回时调用
//        if (currShared == null)
        getConfigAndSet();
        if (!isUpdateImg) {//如果不是更新头像，则从网络获取信息
            getUserInfo();
            getYuEr();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isUpdateImg = false;
    }

    /**
     * 重置所有信息
     */
    private void resetAllData() {
        resetData();
        tvFragmentMeNickname.setText("登录/注册");
        ivFragmentMeHeadimg.setImageResource(R.drawable.myimg2);
        img_level.setVisibility(View.GONE);
    }

    @Override
    public void refresh() {
    }

    //获取配置并且设置
    private void getConfigAndSet() {
//        没有登录直接返回
        if (BaseProtocal.isGoLogin(true)) {
            resetAllData();
            return;
        }
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        String name = sp.getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        codePre = currShared.getString(SpKey.CODEPRE, "");
        codeSuf = currShared.getString(SpKey.CODESUF, "");
        String petName = currShared.getString(SpKey.NC, "");
        String imageAddress = currShared.getString(SpKey.IMAGEADDRESS, "");
        tvFragmentMeNickname.setText(petName);

//        获取本地保存的头像 ,如果是在线修改的用户信息，需要进入到MyZiLiaoFragment之后才能回显，这样可以省掉频繁的网络请求
//        bitmapLoc = MyImageBitmapUtil.getBitmapLoc(name);
//        因为待支付/待付款返回需要通过用户信息接口返回，导致每次切换页面需要调用接口，不需要再保存到本地,每次都从网络获取
//        if (bitmapLoc != null)
//            ivFragmentMeHeadimg.setImageBitmap(CircleUtil.toRoundBitmap(getActivity(), bitmapLoc));
        if (!isUpdateImg) //如果不是更新头像，则从本地加载网络图片
            if (!TextUtils.isEmpty(imageAddress) && !imageAddress.startsWith("null?"))
                Glide.with(this).load(imageAddress).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                        .transform(new GlideCircleTransform(getActivity(), 2, getActivity().getResources().getColor(R.color.white)))
                        .into(ivFragmentMeHeadimg);
    }

    @OnClick({R.id.iv_fragment_me_headimg, R.id.aboutDmh,
            R.id.setting, R.id.invitF, R.id.my_dingdan, R.id.bonus_detail, R.id.myF, R.id.account_deatil, R.id.del,
            R.id.vip, R.id.chognzhi, R.id.fukuan, R.id.fahuo, R.id.shouhuo, R.id.address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_fragment_me_headimg:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                //  修改资料
                UIUtils.startActivity(My_XiuGai_Activity.class, "position", 0);
                break;
            case R.id.setting:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                跳转到设置页面，修改登录密码和支付密码
                UIUtils.startActivity(MySettingActivity.class);
                break;
            case R.id.invitF:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                邀请好友，展示二维码
                getInvitUrl();
                break;
            case R.id.my_dingdan:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                我的订单H5
                UIUtils.startActivity(FoundActivity.class, "found", 5);
                break;
            case R.id.account_deatil:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                账单明细
                UIUtils.startActivity(AccountDetailActivity.class);
                break;
            case R.id.myF:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                我的下级H5
                UIUtils.startActivity(FoundActivity.class, "found", 6);
                break;
            case R.id.bonus_detail:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//               佣金明细
                UIUtils.startActivity(BonusDetailActivity.class);
                break;
            case R.id.aboutDmh:
//               关于数贸服务
                UIUtils.startActivity(AboutActivity.class);
                break;
            case R.id.del:
                onCall(phoneN);
                break;
            case R.id.vip:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                upVip();
                break;
            case R.id.chognzhi:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                chognzhi();
                break;
            case R.id.fukuan:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                fukuan();
                break;
            case R.id.fahuo:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                fahuo();
                break;
            case R.id.shouhuo:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                shouhuo();
                break;
            case R.id.address:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                地址信息
                UIUtils.startActivity(FoundActivity.class, "found", 11);
                break;
        }
    }

    /**
     * 付款
     */
    private void fukuan() {
        UIUtils.startActivity(FoundActivity.class, "found", 7);
    }

    /**
     * 发货
     */
    private void fahuo() {
        UIUtils.startActivity(FoundActivity.class, "found", 8);
    }

    /**
     * 待收货
     */
    private void shouhuo() {
        UIUtils.startActivity(FoundActivity.class, "found", 9);
    }

    /**
     * 充值
     */
    private void chognzhi() {
        UIUtils.startActivity(FoundActivity.class, "found", 10);
    }

    /**
     * 升级VIP
     */
    private void upVip() {
        UIUtils.startActivity(FoundActivity.class, "found", 2);
    }

    /**
     * 获取邀请好友url
     *
     * @return
     */
    @NonNull
    private void getInvitUrl() {
        BaseProtocal.builder(true).getInvitUrl(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String href = jsonObject.optString("href");
                    PrintUtil.printRespones("邀请好友返回信息：" + href);
                    Intent intent = new Intent(getActivity(), My_XiuGai_Activity.class);
                    intent.putExtra("invit", true);
                    intent.putExtra("position", 2);
                    intent.putExtra(SpKey.INVITURL, href);
                    startActivity(intent);
                } catch (JSONException ignored) {
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, codePre, codeSuf);
    }

    public void onCall(String mobile) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
            } else {
                //上面已经写好的拨号方法
                callDirectly(mobile);
            }
        } else {
            //上面已经写好的拨号方法
            callDirectly(mobile);
        }
    }

    private void callDirectly(String mobile) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.CALL");
        intent.setData(Uri.parse("tel:" + mobile));
        startActivity(intent);
    }

    private boolean isUpdateImg;

    /**
     * 接收头像变化的广播
     */
    private void registerImageBroadCase() {
        IntentFilter intent = new IntentFilter();
        intent.addAction("image");
        getActivity().registerReceiver(receiver, intent);
    }

    /**
     * 根据用户id获取用户余额
     * user/getAccount
     */
    private void getYuEr() {
        BaseProtocal.builder(true).getYuEr(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("获取余额", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String acc = jsonObject.optString("account");
                        account = new Gson().fromJson(acc, Account.class);
//                        设置积分余额
                        setMoney(account);
                    } catch (JSONException ignored) {
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    /**
     * 设置余额/佣金/兑换券
     *
     * @param account
     */
    private void setMoney(Account account) {
        String s = String.valueOf(account.balance).split("\\.")[1];
        if (s != null && s.length() == 1)
            yuEr.setText("余额:" + account.balance + "0");
        else
            yuEr.setText("余额:" + account.balance);
        String ss = String.valueOf(account.bonus).split("\\.")[1];
        if (ss != null && ss.length() == 1)
            yongJin.setText("佣金:" + account.bonus + "0");
        else
            yongJin.setText("佣金:" + account.bonus);
        duiHuanQuan.setText("兑换券:" + account.points);
    }

    /**
     * 设置没有登陆时的显示数据
     */
    private void resetData() {

        yuEr.setText("余额:0.00");
        yongJin.setText("佣金:0.00");
        duiHuanQuan.setText("兑换券:0.00");
        unFuKuan.setVisibility(View.GONE);
        unShouHuo.setVisibility(View.GONE);
        unFaHuo.setVisibility(View.GONE);
        tvFragmentMeNickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BaseProtocal.isGoLogin(true, getActivity())) ;
            }
        });
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param /user/userCenter
     */
    private void getUserInfo() {
        BaseProtocal.builder(true).getUserInfo(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("用户信息", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String stateCount = jsonObject.optString("stateCount");
                        StateCount statecount = new Gson().fromJson(stateCount, StateCount.class);
                        String agent = jsonObject.optString("agent");
                        User userInfo = new Gson().fromJson(response, User.class);
                        StoreInfo.getInstance().store(currShared, userInfo);
                        DBManager.getInstance().saveContact2(userInfo.user);
//                        如果用户不是从商城修改个人信息，不需要设置页面，只需要保存用户信息到数据库即可
                        if (!isUpdateImg)
                            setPage(userInfo.user, statecount, agent);
                    } catch (JSONException e) {
                    }
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    private void setPage(Friend friend, StateCount statecount, String agent) {
        if (friend == null) {
            return;
        }
        // 保存到本地
        currShared.edit().putString(SpKey.NC, friend.petName).apply();
        tvFragmentMeNickname.setText(friend.petName);
        if (TextUtils.equals(friend.sex, "1"))
            currShared.edit().putString(SpKey.SEX, "男").apply();
        else
            currShared.edit().putString(SpKey.SEX, "女").apply();
        currShared.edit().putString(SpKey.SR, friend.birthday).apply();
        currShared.edit().putString(SpKey.DQ, friend.address).apply();
        if (!TextUtils.isEmpty(friend.imageAddress) && !friend.imageAddress.startsWith("null?")) {
            Glide.with(this).load(friend.imageAddress).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                    .transform(new GlideCircleTransform(getActivity(), 2, getActivity().getResources().getColor(R.color.white)))
                    .into(ivFragmentMeHeadimg);
        } else
            ivFragmentMeHeadimg.setImageResource(R.drawable.myimg2);
        if (TextUtils.equals(friend.level, "0"))
            img_level.setVisibility(View.GONE);
        else {
            img_level.setVisibility(View.VISIBLE);
            img_level.setImageResource(TextUtils.equals(friend.level, "1") ? R.drawable.v1 : TextUtils.equals(friend.level, "2")
                    ? R.drawable.v2 : TextUtils.equals(friend.level, "3") ? R.drawable.v3 : TextUtils.equals(friend.level, "4") ? R.drawable.v4 : R.drawable.myimg2);
        }
        isUpdateImg = false;
        if (statecount == null) {
            unFuKuan.setVisibility(View.GONE);
            unShouHuo.setVisibility(View.GONE);
            unFaHuo.setVisibility(View.GONE);
            return;
        }
        if (unFuKuan != null) {
            unFuKuan.setVisibility(TextUtils.equals(statecount.one, "0") ? View.GONE : View.VISIBLE);
            unFuKuan.setText(statecount.one);
        }
        if (unFaHuo != null) {
            unFaHuo.setVisibility(TextUtils.equals(statecount.two, "0") ? View.GONE : View.VISIBLE);
            unFaHuo.setText(statecount.two);
        }
        if (unShouHuo != null) {
            unShouHuo.setVisibility(TextUtils.equals(statecount.three, "0") ? View.GONE : View.VISIBLE);
            unShouHuo.setText(statecount.three);
        }

        if (TextUtils.equals(agent, "no"))
            proxyImg.setVisibility(View.GONE);
        else
            proxyImg.setVisibility(View.VISIBLE);
//        OkHttpUtils
//                .get()
//                .url(friend.imageAddress)
//                .build()
//                .execute(new BitmapCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                    }
//
//                    @Override
//                    public void onResponse(Bitmap bitmap, int id) {
// //                因为接口变动和二维码不添加logo原因，不再需要保持头像到本地
////                        MyImageBitmapUtil.saveBitmapLoc(bitmap, name);
//                        ivFragmentMeHeadimg.setImageBitmap(CircleUtil.toRoundBitmap(getActivity(), bitmap));
//                    }
//                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null)
            getActivity().unregisterReceiver(receiver);
    }
}
